package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.server.agent.AgentGeneral;
import com.yanqu.road.utils.string.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

@RestController
@RequestMapping("/game/admin")
public class AdminHelperController {

    /**
     *  Agent 调用
     */
    @ResponseBody
    @RequestMapping(value = "callAgentGeneral", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String callAgent(HttpServletRequest request, @RequestBody JSONObject paramObject){

        String op = paramObject.getString("op");
        String param = paramObject.getString("param");

        List<String> targetList = StringUtils.stringToStringList(op, "\\|");
        List<String> paramList = StringUtils.stringToStringList(param, "\\|");

        boolean success = true;
        Exception error = null;
        try {
            Class<?> agentGeneral = AgentGeneral.class;
            Object invoke = agentGeneral.newInstance();

            Method method;
            try {
                method = agentGeneral.getMethod(targetList.get(1), new Class[]{long.class, String.class});
                method.invoke(invoke, new Object[]{Long.parseLong(paramList.get(0)), paramList.get(1)});
            } catch (Exception ex) {
                success = false;
                ex.printStackTrace();
                error = ex;
            }

        } catch (Exception ex) {
            success = false;
            error = ex;
            ex.printStackTrace();
        }

        if(success){
            return AdminResult.defaultInstance().toJsonString();
        }
        return AdminResult.failMsg(error.getMessage()).toJsonString();
    }
}
